package com.health.system.action.system;

import static com.health.system.javacommon.util.Struts2JsonHelper.outJson;
import static com.health.system.javacommon.util.Struts2JsonHelper.outJsonString;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;
import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

import com.health.system.javacommon.base.BaseStruts2Action;
import com.health.system.javacommon.jquery.JqueryPageHelper;
import com.health.system.javacommon.jquery.ListRange;
import com.health.system.springSecurity.LogonUser;
import com.health.system.javacommon.util.StringTool;
import com.health.system.model.system.Permission;
import com.health.system.model.system.RolePermission;
import com.health.system.service.system.RolePermissionManager;
import com.health.system.springSecurity.UserInfo;

/**
 * <p>Title: 角色对应权限信息 Action</p> 
 * Description: 页面通过Ajax调用Action层,返回JSONO数据
 * Copyright: Copyright (c) 2011-03 
 * Company: 
 * 
 * @author 
 * @version 1.0 
*/

public class RolePermissionAction extends BaseStruts2Action {
	
	private RolePermissionManager rolePermissionManager;
	
	/** 通过spring自动注入 */
	public void setRolePermissionManager(RolePermissionManager manager) {
		this.rolePermissionManager = manager;
	}	
	
	/**
	 * jqGrid使用列表
	 * @throws IOException
	 */
	public void list() throws IOException{
		PageRequest<Map> pr = JqueryPageHelper.createPageRequestForJquery(getRequest());
		Page page = rolePermissionManager.findByPageRequest(pr);
		
		List<RolePermission> RolePermissionlist = (List) page.getResult();
		ListRange<RolePermission> resultList = new ListRange<RolePermission>();
		resultList.setDataRows(RolePermissionlist);
        resultList.setRecords(page.getTotalCount());
        resultList.setRows(page.getPageSize());
		if(page.getTotalCount()%page.getPageSize()>0){
			resultList.setTotal(page.getTotalCount() / page.getPageSize()+1);
		}else{
			resultList.setTotal(page.getTotalCount() / page.getPageSize());
		}
		resultList.setPage(pr.getPageNumber());
		outJson(resultList);
	}

	/**
	 * RolePermission添加
	 * @throws IOException
	 */
	public void save() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			HttpServletRequest request = getRequest();
			String rolePermissionJson = request.getParameter("rolePermissionJson");
			if (null != rolePermissionJson&&!"".equals(rolePermissionJson)) {
				JSONObject jsonobject =JSONObject.fromObject( rolePermissionJson );
				RolePermission rolePermissionobj = (RolePermission)JSONObject.toBean(jsonobject, RolePermission.class); 
				rolePermissionManager.save(rolePermissionobj);
				result.put("success", true);
				result.put("msg", "添加成功!");
			}else{
				result.put("success", false);
				result.put("msg", "添加失败 数据错误!");
			}
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "添加失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	/**
	 * RolePermission修改
	 * @throws IOException
	 */
	public void update() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
			try{
				HttpServletRequest request = getRequest();
				String rolePermissionJson = request.getParameter("rolePermissionJson");
				if (null != rolePermissionJson&&!"".equals(rolePermissionJson)) {
					JSONObject jsonobject =JSONObject.fromObject( rolePermissionJson );
					RolePermission rolePermissionobj = (RolePermission)JSONObject.toBean(jsonobject, RolePermission.class); 
					rolePermissionobj.setId(jsonobject.get("id").toString());
					rolePermissionManager.update(rolePermissionobj);
					result.put("success", true);
					result.put("msg", "修改成功!");
				}else{
					result.put("success", false);
					result.put("msg", "修改失败 数据错误!");
				}
			}catch (Exception e){
				result.put("success", false);
				result.put("msg", "修改失败!");
				e.printStackTrace();
			}
		outJson(result);
	}
	
	/**
	 * RolePermission删除
	 * @throws IOException
	 */
	public void delete() throws IOException{
		String id = getRequest().getParameter("id");
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			if (null != id&&!"".equals(id)){
				rolePermissionManager.removeById(id);
				result.put("success", true);
				result.put("msg", "删除成功");
			}else{
				result.put("success", false);
				result.put("msg", "删除失败 数据错误!");
			}
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "删除失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	/**
	 * 角色权限树(刘文辉)
	 * @throws IOException
	 */
	public void getRolePermissionTree() throws IOException {
		
		String result="",id="",parentId="",name="";
		Map mmsMp = new HashMap();
        Map subMp = new HashMap();
        List sublist = new ArrayList();
        
        Hashtable roleperhash = new Hashtable(); //角色权限哈希
		Permission permission = new Permission(); 
		RolePermission rolePermission = new RolePermission(); 
		
		List permissionList = null;
		List rolePermissionList = null;
		
		HttpServletRequest request = getRequest();
		try{
			String sort = request.getParameter("sort"); //权限元素
			String roleId = request.getParameter("roleId"); //角色ID
			if(null!=roleId){
				roleId.replaceAll(" ", "");
				roleId.replaceAll("null", "");
			}
			Permission peron = new Permission(); 
			RolePermission roleperon = new RolePermission(); 
			
			if (sort!=null && sort.length()>0) {
				peron.setSort(sort);
			}else {
				throw new Exception("参数错误 权限类别为空!");
			}
			
			if (roleId.length()>0) {
				roleperon.setRoleId(roleId);
			}else {
				throw new Exception("参数错误 角色ID为空!");
			}
			
			roleperon.setPermission(peron);
			/**查询权限列表*/
			Map  mapParam = new HashMap();
			mapParam.put("sort", sort); //  权限类型
			//从登录用户类中取当前用户信息
			UserInfo userInfo = LogonUser.logonUser();
			String userId = "";
			if(null!=userInfo){
				userId = userInfo.getUserId();
			}
			/**如果是超级管理员不加条件查询*/ 
//			if(ParamUtil.isSuperManager()){
			    permissionList    = rolePermissionManager.getPermissionByMap(mapParam);
//			}else{
//				mapParam.put("userId", userId); // 操作员ID
//				permissionList    = rolePermissionManager.getPermissionByMap(mapParam);
//			}
			/**查询角色对应的权限*/
			rolePermissionList =rolePermissionManager.getRolePermissionList(roleperon);
			
			for (int i = 0; rolePermissionList != null && i < rolePermissionList.size(); i++) {
				rolePermission = (RolePermission)rolePermissionList.get(i);
				roleperhash.put(rolePermission.getPermissionId(), rolePermission);
			}

			for (int i = 0; permissionList != null && i < permissionList.size(); i++) {
				permission = (Permission)permissionList.get(i);
				id=permission.getId();
				parentId=permission.getParentId();
				name=permission.getDescription();
			//	if(i==0||parentId.equals("0")){
					if(result==""){
						if(roleperhash.containsKey(id)){
							result ="{name:'"+name+"',checked:true,id:'"+id+"'}";
						}else{
							result ="{name:'"+name+"',id:'"+id+"'}";
						}
	            	}else{
	            		if(roleperhash.containsKey(id)){
							result +=",{name:'"+name+"',checked:true,id:'"+id+"'}";
						}else{
							result +=",{name:'"+name+"',id:'"+id+"'}";
						}
	            	}
			//		mmsMp.put(id, name);
			//	}else{
	        //    	sublist.add(permission);
			//	}
			}
			if(sublist.size()>0){
	        //	result=getSubTree(sublist,mmsMp,roleperhash,result);
	        }
		}catch (Exception e){
			result="";
			e.printStackTrace();
		}
		outJsonString("["+result+"]");
	}
	
	private String getSubTree(List sublist,Map subMp,Map roleperhash,String result) {
		String id="",parentId="",name="";
		Permission permission = new Permission(); 
		Map Mp = new HashMap();
        List slist = new ArrayList();
        try{
         for (int i = 0; i < sublist.size(); i++) { //遍历所有子节点
        	permission = (Permission)sublist.get(i);
			id=permission.getId();
			parentId=permission.getParentId();
			name=permission.getDescription();
			
			if(subMp.containsKey(parentId)){
	            String tmpstr="",tmpstr1="",tmpstr2="",tmpstr3="";
	            if(roleperhash.containsKey(id)){
	            	tmpstr ="{name:'"+name+"',checked:true,id:'"+id+"'}";
	            }else{
	            	tmpstr ="{name:'"+name+"',id:'"+id+"'}";
	            }
	            if(result.indexOf("id:'"+parentId+"',nodes")!=-1){
	    			tmpstr1 =result.substring(0,result.indexOf("id:'"+parentId+"',nodes"));
	    			String str =result.substring(result.indexOf("id:'"+parentId+"',nodes"),result.length());
	    			tmpstr1 +=str.substring(0, str.indexOf("]"));
	    			tmpstr2 =","+tmpstr;
	    			tmpstr3 =str.substring(str.indexOf("]"),str.length());
	    		}else{
	    			tmpstr1 =result.substring(0,result.indexOf("id:'"+parentId+"'")+("id:'"+parentId+"'").length());
	        		tmpstr2 =",nodes:["+tmpstr+"]";
	        		tmpstr3 =result.substring(result.indexOf("id:'"+parentId+"'")+("id:'"+parentId+"'").length(),result.length());
	    		}
	    		result =tmpstr1+tmpstr2+tmpstr3;
	    		Mp.put(id, name);
	        }else{
	        	slist.add(permission);
        	}
         }
         if(slist.size()>0){
        	result=getSubTree(slist,Mp,roleperhash,result);
         }
        }catch(Exception exe ){
        	exe.printStackTrace();
        }
		return result;
	}
	
	/**
	 * 删除添加角色权限（刘文辉）
	 * @throws IOException
	 */
	public void deleterolePermission() throws IOException{
		
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			RolePermission rolePermission = new RolePermission(); 
			HttpServletRequest request = getRequest();
			String sort = request.getParameter("sort"); //权限元素
			String roleId = request.getParameter("roleId"); //角色
			String permissionIdarr=request.getParameter("permissionIdarr");  //权限ID
			
			
			if (sort!=null && !"".equals(sort)) {
				Permission permission = new Permission();
				permission.setSort(sort);
				rolePermission.setPermission(permission);
			}else {
				throw new Exception("参数错误 权限类型有误");
			}
			
			if (roleId!=null && !"".equals(roleId)) {
				rolePermission.setRoleId(roleId);
			}else {
				throw new Exception("参数错误 角色ID有误");
			}
			
			if (permissionIdarr!=null && !"".equals(permissionIdarr)) {
				rolePermission.setPermissionList(StringTool.stringToArray(permissionIdarr));
			}else {
				throw new Exception("参数错误 权限ID有误");
			}

			if(rolePermissionManager.deletesave(rolePermission)){
				result.put("success", true);
				result.put("msg", "保存成功!");
			}else{
				result.put("success", false);
				result.put("msg", "保存失败!");
			}
			
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "保存失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	
}
